<script setup>
import {ref, onMounted, computed, watch} from 'vue'
import {storeToRefs} from 'pinia'
import {useMessage} from "naive-ui"
import {useUserProfile} from "@/stores/useUserProfile.js";

const userProfile = useUserProfile()
const {setUserProfile, openTestcase} = userProfile
const {profile, selectedVersion} = storeToRefs(userProfile)
const {addTestcase, removeTestcase, saveTestcase} = userProfile


const contextTarget = ref(null)
const override = ({option}) => {
	if (option.children) {
		return "toggleExpand";
	}
	return "default";
};

// 从pinia中获取用例集
const testcases = computed(() => profile.value.testcases || [])
const message = useMessage();

// 用于显示菜单的标志以及菜单显示坐标位置相关
const showDropdownRef = ref(false);
const xRef = ref(0);
const yRef = ref(0);
// 测试用例表单
const testcaseModel = ref({
	id: 1,
	label: null,
	createTime: "2024-02-02",
	modifyTime: "2020-01-02",
	author: null,
	remark: null,
	// 指令相关
	commandList: [],
	commandVersion: selectedVersion.value.optical.command
})
/**
 * id: "xxx",
 * label: "热实验",
 * createTime: "2020-01-01",
 * lastUpdate: "2020-01-02",
 * author: "zzy",
 * remark: "xxx"
 */

// 建立用例的回调(模态框点击确认触发)
const submitCallback = () => {
	// 不存在则新建,存在则修改
	if (contextTarget.value?.key) {
		saveTestcase({
			...testcaseModel.value,
			key: testcaseModel.value.label,
			modifyTime: new Date().toLocaleString()
		})
		message.success("修改成功!")
	} else {
		// 持久化用例到pinia
		addTestcase({
			key: testcaseModel.value.label, ...{
				...testcaseModel.value,
				createTime: new Date().toLocaleString()
			}
		})
		// 设置当前用例为打开状态
		setUserProfile("currentTestcase", profile.value.testcases[0].children.at(-1))
		message.success("新建用例成功!")
	}


	showModal.value = false
}

// 处理右击菜单的选择事件
const handleSelect = (key) => {
	if (key === "create-modify") {
		if (contextTarget.value?.readOnly) {
			message.warning("只读用例无法修改!")
			return;
		}
		// 新建用例显示模态框
		showModal.value = true
		// 把表单值变为当前值
		if (contextTarget.value && contextTarget.value?.key) {
			testcaseModel.value = contextTarget.value
		}
	} else if (key === "delete") {
		// 删除当前右击的用例
		let targetIndex = testcases.value[0].children.indexOf(contextTarget.value)
		if (targetIndex === -1) {
			console.log("未找到指定元素无法删除!")
			message.warning("当前没有选择任何目标无法删除, 请确保右击到元素位置!")
			showDropdownRef.value = false
			return
		} else if (profile.value.currentTestcase.key === contextTarget.value.key) {
			message.error("该用例正在使用中,无法删除!")
			return;
		} else if (contextTarget.value?.readOnly) {
			message.error("该用例为系统预置,不可删除!")
			return;
		}
		// 重置上下文目标
		contextTarget.value = null
		// 清除当前打开的用例
		setUserProfile("currentTestcase", {commandList: []})

		showDropdownRef.value = false
		removeTestcase(targetIndex)
	}
}


const handleClickoutside = () => {
	showDropdownRef.value = false
}

// 注入到NTree组件中的事件
const nodeProps = ({option}) => {
	return {
		onClick() {
			// 不包含根节点
			if (option.children) return
			// 设置为当前用例
			// setUserProfile("currentTestcase", option)
			openTestcase(option.key)
			message.info(`打开了${option.key}的用例!`)
			// 切换用例显示
		},
		onContextmenu(e) {
			console.log(option)
			// 获取右击时元素的选项值
			contextTarget.value = option
			showDropdownRef.value = true
			xRef.value = e.clientX
			yRef.value = e.clientY
			console.log(e.clientX, e.clientY)
			e.preventDefault()
		}
	}
}

// 右击菜单的选项
const options = [
	{
		key: "create-modify",
		label: "新建/修改",
	},
	{
		label: "删除",
		key: "delete"
	}
]

// first_tc
const lastTestcase = computed({
	get: () => profile.value.currentTestcase.key,
	set: (value) => {
		console.log(value)
	}
})
const showModal = ref(false)


// 右击空白区域的回调
const onTreeContextMenu = (e) => {
	// 如果点击区域不是树节点，触发空白区域的菜单
	if (e.target === e.currentTarget) {
		// 非树节点, 需要使右击目标置空, 否则造成误删
		contextTarget.value = null
	}
	showDropdownRef.value = true
	xRef.value = e.clientX
	yRef.value = e.clientY
	e.preventDefault()
}
const treeRef = ref(null)
onMounted(() => {
	let last = profile.value.testcases[0].children.at(-1)
	console.log(last.key)
	console.log(treeRef.value)
	// console.log(testcases)
	// console.log(treeRef.value)

})

function isObjectsEqual(obj1, obj2, ignoreKeys = []) {
	const keys = new Set([...Object.keys(obj1), ...Object.keys(obj2)])

	for (const key of keys) {
		if (ignoreKeys.includes(key)) continue

		const val1 = obj1[key]
		const val2 = obj2[key]

		if (JSON.stringify(val1) !== JSON.stringify(val2)) {
			return false
		}
	}

	return true
}


const previousKey = ref("")

watch(
	() => ({
		key: profile.value.currentTestcase.key,
		commands: profile.value.currentTestcase.commandList
	}),
	({key, commands}, old) => {
		if (key !== old.key) {
			previousKey.value = key
			return // 是用例切换，忽略
		}

		console.log("用例修改了")
		profile.value.currentTestcase.modifyTime = new Date().toLocaleString()
	},
	{deep: true}
)


</script>

<template>
	<!--用例树容器-->
	<div @contextmenu="onTreeContextMenu" class="bg-zinc-800/50 min-h-48">
		<n-tree
			:node-props="nodeProps"
			v-model:selected-keys="lastTestcase"
			ref="treeRef"
			block-line
			show-line
			default-expand-all
			:data="testcases"
			:override-default-node-click-behavior="override"
		/>
	</div>


	<n-dropdown
		placement="bottom-start"
		trigger="manual"
		:x="xRef"
		:y="yRef"
		:options="options"
		:show="showDropdownRef"
		@select="handleSelect"
		@clickoutside="handleClickoutside"
	/>
	<n-modal
		v-model:show="showModal"
		preset="dialog"
		class="ps-4 pe-4"
		content-class="flex flex-col"
		positive-text="确认"
		negative-text="算了"
		@positive-click="submitCallback"
	>
		<template #header>
			<n-text v-if="contextTarget?.key">
				修改用例
				<!--				{{ testcases[0].children[testcases[0].children.indexOf(contextTarget)]?.label }}-->
			</n-text>
			<n-text v-else>新建用例</n-text>

		</template>
		<template #default>
			<n-form-item label="用例名称:">
				<n-input v-model:value="testcaseModel.label" placeholder="请输入用例名称"></n-input>
			</n-form-item>
			<n-form-item label="创建人:">
				<n-input v-model:value="testcaseModel.author"></n-input>
			</n-form-item>
			<n-form-item label="备注">
				<n-input v-model:value="testcaseModel.remark" placeholder="选填"></n-input>
			</n-form-item>
			<n-text class="ms-auto" depth="3">指令版本基于{{ selectedVersion.optical.command }}</n-text>
		</template>
	</n-modal>
</template>

<style scoped>

</style>